import http from '../api/httpRequest.js'
import userStore from './userStore';
export default {

	state: {
		groups: [],
		activeGroup: null,
	},
	mutations: {
		setGroups(state, groups) {
			state.groups = groups;
		},
		activeGroup(state, idx) {
			state.activeGroup = state.groups[idx];
		},
		addGroup(state, group) {
			state.groups.unshift(group);
		},
		removeGroup(state, groupId) {
			state.groups.forEach((g, idx) => {
				if (g.id == groupId) {
					state.groups.splice(idx, 1);
				}
			})
			if (state.activeGroup && state.activeGroup.id == groupId) {
				state.activeGroup = null;
			}
		},
		updateGroup(state, group) {
			state.groups.forEach((g, idx) => {
				if (g.id == group.id) {
					// 拷贝属性
					Object.assign(state.groups[idx], group);
				}
			})
		},
		clear(state) {
			state.groups = [];
			state.activeGroup = null;
		},
		updateGroupMemberProhibition(state, { groupId, userId, prohibition }) {
			// 更新群组列表中的成员状态
			const group = state.groups.find(g => g.id === groupId);
			if (group && group.groupMembers) {
				const member = group.groupMembers.find(m => m.userId === userId);
				if (member) {
					member.prohibition = prohibition;
				}
			}
			// 更新当前激活群组中的成员状态
			if (state.activeGroup && state.activeGroup.id == groupId) {
				const member = state.activeGroup.groupMembers.find(m => m.userId == userId);
				if (member) {
					member.prohibition = prohibition;
				}
			}
		}
	},
	actions: {
		loadGroup(context) {
			return new Promise((resolve, reject) => {
				http({
					url: '/group/list',
					method: 'GET'
				}).then((groups) => {
					if(context){
						context.commit("setGroups", groups);
					}
					resolve(groups);
				}).catch((res) => {
					reject(res);
				})
			});
		},
		findGroups(params,context){
			return new Promise((resolve, reject) => {
				http({
					url: `/group/find/` + params.gid,
					method: 'GET'
				}).then((data) => {
					if(data){
						if(data.ownerId===params.uid){
							data.remark=data.name;
							data.isAdmin=true;
						}else{
							data.isAdmin=false;
						}
						// 更新聊天列表的群聊信息
						//this.updateGroup(data);
						context.commit("updateGroup", data);
						userStore.actions.updateChatFromGroup(data);
						resolve(data);
					}
					resolve();
				}).catch((res) => {
					reject(res);
				})
			});
		},findGroups2(context,params){
			return new Promise((resolve, reject) => {
				http({
					url: `/group/find/` + params.gid,
					method: 'GET'
				}).then((data) => {
					if(data){
						context.commit("updateGroup", data);
						resolve(data);
					}
					resolve();
				}).catch((res) => {
					reject(res);
				})
			});
		},
	}
}